/**
 * Lockbox
 * A Password and Secret Information Manager.
 *
 * This class shows files to be imported into Lockbox and performs
 * the actual import.
 *
 * Creator:	Carsten Heinelt
 * Version:	16-Feb-2008
 */

#import "LockboxApp.h"
#import "LockboxOptions.h"
#import "LockboxImportView.h"
#import <unistd.h>
#import <sys/stat.h>

@implementation LockboxImportView

- (void)dealloc {
  [navBar release];
  [navTitle release];
  [table release];
  [delegate release];
  [files release];
  
  [super dealloc];
}

/**
 *	Constructor
 */
- (id)initWithFrame:(struct CGRect)frame app:(id)app;{
  self = [super initWithFrame:frame];
  if (self) {
    NSLog(@"LockboxImportView initWithFrame entered");
    delegate = app;

    _storage = [LockboxStorage globalInstance];
    [self getFiles];


    // Create navigation bar
    navBar = [[UINavigationBar alloc] 
      initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, NAVBAR_HEIGHT)];
    [navBar showButtonsWithLeftTitle: @"Options" rightTitle:NULL leftBack: TRUE];
    [navBar setBarStyle: 3];
    [navBar enableAnimation];
    [navBar setDelegate: self];
    
    // Create navigation bar title
    navTitle = [[UINavigationItem alloc] initWithTitle:@"Import CSV File"];
    [navBar pushNavigationItem:navTitle];

    // Create preferences table
    table = [[UIPreferencesTable alloc] 
      initWithFrame:CGRectMake(0.0f, 45.0f, 320.0f, 415.0f)];
	  [table setDataSource:self];
    [table setDelegate:self];
    [table reloadData];

    [self addSubview:navBar];
    [self addSubview:table];
    NSLog(@"LockboxImportView initWithFrame leaving");
  }

  return self;
}

/**
 * Retrieve a list of files to import in the Lockbox home directory
 */
- (void)getFiles;
{
  NSString *importPath = [LockboxOptions homedir];
  NSLog(@"LockboxImportView getFiles path=%@", importPath);
  files = [[[NSFileManager defaultManager] 
    directoryContentsAtPath:importPath 
    matchingExtension:@"csv"
    options:0
    keepExtension:TRUE] retain];
  //files = [[NSMutableArray alloc] initWithArray:foundFiles];
  NSLog(@"LockboxImportView getFiles files found=%d", [files count]);
}

/**
 * Check whether table row can be deleted -> always YES
 */
- (BOOL) table:(UITable *) table canDeleteRow:(int) row {
  return YES;
}

/**
 * Check whether table row can be moved -> always YES
 */
- (BOOL) table:(UITable *) table canMoveRow:(int) row {
  return YES;
}

/**
 * tableRowSelected
 *
 * Select a new row.
 */
- (void)tableRowSelected:(NSNotification *)notification {
  int row = [table selectedRow];
  NSLog(@"LockboxImportView tableRowSelected:%d", row);
  if ([files count] > 0 && row>0 && row <= [files count]) {
    NSString *csvFilePath = 
        [[LockboxOptions homedir] stringByAppendingFormat:@"/%@", [files objectAtIndex:(row-1)]];
    UIAlertSheet *infoSheet = [[[UIAlertSheet alloc] initWithFrame:CGRectMake(0, 0, 0, 0)] autorelease];
    NSString* msg;
    @try {
        [_storage loadCSV:csvFilePath];
        if(![self eraseFile:csvFilePath])
            [NSException raise:NSFileIOException format:@"Unable to erase CSV file"];
        [[delegate getListView] refresh];
        [[delegate getOptionsView] refresh];
        [files removeObjectAtIndex:(row-1)];
        [table deleteRows:NULL viaEdge:row];
        msg = [NSString stringWithFormat:@"Successfully imported and removed\n%@", csvFilePath];
        [infoSheet setTitle:@"CSV Import"];
    }
    @catch (NSException* ex) {
      NSLog(@"***Caught exception during loadCSV: %@ reason: %@", [ex name], [ex reason]);
      msg = [NSString stringWithFormat:@"Error: %@", [ex reason]];
      [infoSheet setTitle:@"Error"];
    }
    [infoSheet setBodyText:msg];
    [infoSheet addButtonWithTitle:@"OK"];
    [infoSheet setDelegate:self];
    [infoSheet setAlertSheetStyle:1];
    [infoSheet presentSheetFromBehindView:self];
    [table selectRow: -1 byExtendingSelection: NO withFade: YES];
    //[delegate transitionToView:[delegate getOptionsView] withTransition:2];
	}
}

/**
  * eraseFile
  *
  * Erase a file by overwriting it and then deleting it
  */
- (BOOL)eraseFile:(NSString*)filePath {
	struct stat statbuf;
	NSLog(@"Entered eraseFile: %@", filePath);
	int fileHandle = open([filePath cString], O_RDWR);
	if(fileHandle>0) {
	  NSLog(@"eraseFile: file %@ successfully opened", filePath);
    lseek(fileHandle, 0, SEEK_SET);
    if(fstat(fileHandle, &statbuf)>=0) {
      char buf[1];
      buf[0] = '\0';
	    NSLog(@"eraseFile: buffer defined and filled");
      int count = statbuf.st_size;
	    NSLog(@"eraseFile: file has size %d", count);
      while(count>0) {
        write(fileHandle, &buf, 1);
        count--;
      }
    }
		close(fileHandle);
	} else
	  return FALSE;
	NSLog(@"eraseFile: removing file");
  // remove the CSV file so that it does not get imported again
  [[NSFileManager defaultManager] removeFileAtPath:filePath handler:nil];
	NSLog(@"eraseFile: leaving");
	return TRUE;
}

/**
 * Get number of preferences groups in table.
 */
- (int)numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
	return 1;
}

/**
 * Get number of rows in preferences groups in table.
 */
- (int)preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
	if(group == 0) {
    NSLog(@"LockboxImportView number of rows:%d", [files count]);
		// All files
		return [files count];
	}
}

/**
 * Get table cell in group.
 */
- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForGroup:(int)group {
	UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
	
  NSLog(@"LockboxImportView get table cell");
	return [cell autorelease];
}

/**
 * Get table cell in group.
 */
- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
  NSLog(@"LockboxImportView get table cell entered: group=%d row=%d", group, row);
	if (group == 0) {
		if ([files count] > 0 && row>=0 && row < [files count]) {
      NSLog(@"LockboxImportView get table cell:%d %@", row, [files objectAtIndex:row]);
			UIPreferencesControlTableCell *cell = [[UIPreferencesControlTableCell alloc] 
			  initWithFrame:CGRectMake(0, 0, 320, 45)];

			cell = [[[UIPreferencesTableCell alloc] init] retain];
			[cell setTitle:(NSString*)[files objectAtIndex:row]];
			[cell setAlignment:1];
			[cell setShowDisclosure:NO];
			return [cell autorelease];
		}
	}
  NSLog(@"LockboxImportView get table cell: leaving");
  return NULL;
}

/**
 * Get table cell height.
 */
- (float)preferencesTable:(UIPreferencesTable *)aTable 
    heightForRow:(int)row 
    inGroup:(int)group 
    withProposedHeight:(float)proposed {
  return proposed;
}

/**
 *  Action on pressed back button.
 */
- (void)navigationBar:(UINavigationBar*)navbar buttonClicked:(int)button
{
  switch (button) {
    case 1: // Back    {
      [delegate transitionToView:[delegate getOptionsView] withTransition:2];
      break;
    }
  }
}

/**
 *  Action on pressed OK button in alert sheet.
 */
- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button
{
    [sheet dismiss];
}

@end
